<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, FormInstance, FormRules, UploadProps } from 'element-plus';
import useStore from '@/store';
import { props } from './form';
defineOptions({ name: 'UserForm' });
const _props = defineProps(props);
const save = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      window.$api.user.save(form).then(res => {
        ElMessage.success('保存成功!');
        useStore.window.windowRemove(_props.window?.name);
        if (_props.window?.callBack) _props.window?.callBack();
      });
    }
  });
};
const imageUrl = ref('');
const organizations = ref([]);
const users = ref([]);
const educations = ref([]);
const employeeStatuss = ref([]);
const treeRef = ref(null);
const ruleFormRef = ref<FormInstance>();
const form = reactive({
  id: null,
  organizationIds: [],
  name: null,
  userName: null,
  password: null,
  remark: null,
});
const rules = reactive<FormRules>({
  organizationIds: [{ required: true, message: '请选择所属组织机构', trigger: 'change' }],
  name: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { max: 50, message: '不能多于50个字符', trigger: 'blur' },
  ],
});
/** 加载基础数据,字典等 */
const init = async () => {
  await window.$api.organization.query().then(res => {
    organizations.value = res.data;
  });
};
const detail = () => {
  window.$api.user.detail(_props.window.params.id).then(res => {
    form.id = res.data.id;
    form.organizationIds = res.data.organizationIds;
    form.name = res.data.name;
    form.userName = res.data.userName;
    form.password = res.data.password;
    form.remark = res.data.remark;
  });
};
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
  const type = ['image/jpeg', 'image/jpg', 'image/png'];
  if (type.indexOf(rawFile.type) === -1) {
    ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};
const uploadAction = async option => {
  let params = new FormData();
  params.append('file', option.file);
  await window.$api.attachment.uploadEmployeePhoto(params).then(res => {
    form.attachmentId = res.data.attachmentId;
    imageUrl.value = res.data.attachmentPath;
  });
};
onMounted(() => {
  init();
  if (_props.window.params) {
    if (_props.window.params.id) {
      detail();
    }
  }
});
</script>

<template>
  <windows-window :window="window">
    <template #button>
      <windows-button-group size="18">
        <windows-button icon="fluent-save-28-regular" @click="save"></windows-button>
      </windows-button-group>
    </template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px" size="default" status-icon>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属机构" prop="organizationIds">
            <el-tree-select
              ref="treeRef"
              v-model="form.organizationIds"
              node-key="id"
              :data="organizations"
              :props="{
                children: 'children',
                label: 'name',
              }"
              multiple
              highlight-current
              default-expand-all
              check-strictly
            ></el-tree-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户账号" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </windows-window>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
<style scoped lang="scss">
#edit {
  height: 100%;
}
.el-form {
  margin: 30px 20px;
}
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.custom-node {
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
.select-icon {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  margin-top: 5px;
  background: #fff;
  width: 100%;
  height: 200px;
  overflow: auto;
  .el-image {
    margin: 10px;
    cursor: pointer;
    border-radius: 5px;
    padding: 5px;
    &:hover,
    &.active {
      background: #dcdfe6;
    }
  }
}
</style>
